﻿using IM.Easy.Core.Attributes;
using IM.Easy.Entity.Gen;
using IM.Easy.GenServices.Dtos;
using IM.Easy.GenServices.IServices;
using IM.Easy.GenServices.Services;
using IM.Easy.Infrastructure.Query;
using Mapster;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Net.Mime;

namespace IM.Easy.Api.Controllers.Gen
{
    [Route("api/gen")]
    public class GenTableController : ControllerBase
    {
        private readonly IGenTableService _genTableService;
        private readonly IGenService _genService;
        public GenTableController(IGenTableService genTableService, IGenService genService)
        {
            _genTableService = genTableService;
            _genService = genService;
        }

        [HttpGet("table/{id}")]
        public GenTableDto GetGenTable([FromRoute] Guid id)
        {
            return _genTableService.GetGenInfo(id);
        }

        [HttpPost("table/import")]
        public void GenTable([FromBody] List<DbTableDto> dbTables)
        {
            foreach (var item in dbTables)
            {
                var table = _genTableService.GetDbTable(item.Name);
                var genTable = _genService.GenTableInfo(table);
                _genTableService.InsertGenTable(genTable);
            }
        }

        [HttpPut("table")]
        public bool Update([FromBody] GenTableDto dto)
        {
            var genTable = dto.Adapt<GenTable>();
            return _genTableService.UpdateGenInfo(genTable);
        }

        [HttpGet("table")]
        public PageResponse<GenTableDto> GetList([FromQuery] GenTableQueryDto query)
        {
            return _genTableService.GetList(query);
        }

        /// <summary>
        /// 获取数据库列表
        /// </summary>
        /// <returns></returns>
        [HttpGet("db/list")]
        public PageResponse<DbTableDto> GetDbTableList(DbTableQueryDto query)
        {
            return _genTableService.GetDbTableList(query);
        }

        [HttpGet("code/{id}")]
        public FileStreamResult Gen([FromRoute] Guid id)
        {
            var dto = _genTableService.GetGenInfo(id);
            var model = _genService.GetGenModel(dto);
            var zipFileStream = _genService.Gen(model);
            // 设置响应头，以便浏览器识别为 ZIP 文件下载
            var zipFileName = "files.zip";
            return File(zipFileStream, MediaTypeNames.Application.Zip, zipFileName);
        }

        /// <summary>
        /// 删除表
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete("table/{id}")]
        public bool Delete([FromRoute] Guid id)
        {
            return _genTableService.Delete(id);
        }
    }
}
